<template>
  <div class="app-container">
    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="8" :md="8">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <el-icon class="stat-icon" color="#409EFF"><Document /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalTasks }}</div>
              <div class="stat-label">发布任务</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8" :md="8">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <el-icon class="stat-icon" color="#67C23A"><User /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ stats.personCount }}</div>
              <div class="stat-label">人员数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8" :md="8">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <el-icon class="stat-icon" color="#909399"><DataAnalysis /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ Math.round(stats.completionRate * 100) }}%</div>
              <div class="stat-label">完成率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :md="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="card-header">
              <el-icon><DataAnalysis /></el-icon>
              <span class="card-title">任务统计趋势</span>
            </div>
          </template>
          <!-- 增加内联尺寸兜底，避免初次宽高为 0 -->
          <div ref="taskTrendChart" class="chart-container" style="height:350px;width:100%;"></div>
        </el-card>
      </el-col>

      <el-col :xs="24" :md="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="card-header">
              <el-icon><CircleCheck /></el-icon>
              <span class="card-title">任务完成情况</span>
            </div>
          </template>
          <div ref="completionChart" class="chart-container" style="height:350px;width:100%;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近任务列表 -->
    <el-row>
      <el-col :span="24">
        <el-card class="table-card" shadow="never">
          <template #header">
            <div class="card-header">
              <span class="card-title">最近任务</span>
              <el-button type="primary" size="small" @click="goToTaskList">查看全部</el-button>
            </div>
          </template>
          <el-table :data="recentTasks" style="width: 100%" stripe>
            <el-table-column prop="id" label="任务编号" width="100" align="center" />
            <el-table-column prop="name" label="任务" />
            <el-table-column prop="description" label="任务类型" width="120" align="center" />
            <el-table-column prop="publishTime" label="发布时间" width="160" align="center" />
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag size="small" :type="row.status === '已停用' ? 'info' : 'success'">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onBeforeUnmount, onActivated } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { Document, DataAnalysis, CircleCheck, User } from '@element-plus/icons-vue'
import { listTask } from '@/api/peach/task'

const router = useRouter()

// 图表 DOM 引用
const taskTrendChart = ref(null)
const completionChart = ref(null)

// ECharts 实例
let trendInstance = null
let completionInstance = null

// 最近任务
const recentTasks = ref([])

// 统计状态
const stats = ref({
  totalTasks: 0,
  personCount: 0,
  completionRate: 0, // 0~1
  buckets: { // 饼图
    completed: 0,
    inProgress: 0,
    notStarted: 0,
    disabled: 0
  },
  trend: { // 折线图
    months: [],
    publishedSeries: [],
    finishedSeries: []
  }
})

// 跳转到任务列表页面
const goToTaskList = () => {
  router.push('/task')
}

// 拉取最近任务（取最新的 5 条）
const loadRecentTasks = async () => {
  const queryParams = { pageNum: 1, pageSize: 5 }
  const res = await listTask(queryParams).catch(() => ({}))
  const rows = Array.isArray(res?.rows) ? res.rows : []

  const parseDate = (s) => (s ? new Date(s) : new Date(0))
  const toDateTime = (s) => {
    if (!s) return ''
    const d = new Date(s)
    const pad = (n) => (n < 10 ? '0' + n : '' + n)
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
  }

  rows.sort((a, b) => {
    const ta = parseDate(a.createTime || a.startTime).getTime()
    const tb = parseDate(b.createTime || b.startTime).getTime()
    return tb - ta
  })

  recentTasks.value = rows.map((t) => ({
    id: t.taskId,
    name: t.taskName,
    description: t.description,
    publishTime: toDateTime(t.createTime || t.startTime),
    status: t.status === 1 ? '进行中' : '已停用'
  }))
}

// 拉取所有任务
const fetchAllTasks = async () => {
  let pageNum = 1
  const pageSize = 200
  let total = Infinity
  const all = []

  while ((pageNum - 1) * pageSize < total) {
    const res = await listTask({ pageNum, pageSize }).catch(() => ({}))
    const rows = Array.isArray(res?.rows) ? res.rows : []
    total = Number(res?.total ?? rows.length)
    all.push(...rows)
    if (rows.length < pageSize) break
    pageNum++
  }
  return all
}

// 构建近N个月序列（含当月）
const buildRecentMonths = (n = 10) => {
  const out = []
  const now = new Date()
  for (let i = n - 1; i >= 0; i--) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1)
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    out.push(`${y}-${m}`)
  }
  return out
}

// 统计聚合
const loadTaskStats = async () => {
  let tasks = []
  try {
    tasks = await fetchAllTasks()
  } catch (e) {
    console.error('loadTaskStats error:', e)
    tasks = []
  }

  const now = new Date()
  const totalTasks = tasks.length
  const personIds = new Set()

  let completed = 0
  let inProgress = 0
  let notStarted = 0
  let disabled = 0

  // 趋势桶
  const months = buildRecentMonths(10)
  const pubMap = new Map(months.map(m => [m, 0]))
  const finMap = new Map(months.map(m => [m, 0]))

  const monthKey = (d) => {
    if (!d) return null
    const dt = new Date(d)
    if (isNaN(dt)) return null
    return `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}`
  }

  for (const t of tasks) {
    if (t.userId != null) personIds.add(t.userId)

    const st = t.startTime ? new Date(t.startTime) : null
    const et = t.endTime ? new Date(t.endTime) : null
    const status = Number(t.status ?? 1)

    // 饼图分类
    if (status === 0) {
      disabled++
    } else if (et && et.getTime() < now.getTime()) {
      completed++
    } else if (st && st.getTime() > now.getTime()) {
      notStarted++
    } else {
      inProgress++
    }

    // 发布趋势
    const pubK = monthKey(t.createTime)
    if (pubK && pubMap.has(pubK)) pubMap.set(pubK, pubMap.get(pubK) + 1)

    // 完成趋势
    const finK = monthKey(t.endTime)
    if (finK && finMap.has(finK) && et && et.getTime() < now.getTime()) {
      finMap.set(finK, finMap.get(finK) + 1)
    }
  }

  const personCount = personIds.size
  const denom = (completed + inProgress + notStarted) // 不含停用
  const completionRate = denom > 0 ? completed / denom : 0

  stats.value = {
    totalTasks,
    personCount,
    completionRate,
    buckets: { completed, inProgress, notStarted, disabled },
    trend: {
      months,
      publishedSeries: months.map(m => pubMap.get(m) ?? 0),
      finishedSeries: months.map(m => finMap.get(m) ?? 0)
    }
  }
}

// 统一 resize 处理
const handleResize = () => {
  trendInstance && trendInstance.resize()
  completionInstance && completionInstance.resize()
}

// 初始化任务统计趋势图
const initTaskTrendChart = () => {
  if (!taskTrendChart.value) return
  if (trendInstance) {
    trendInstance.dispose()
    trendInstance = null
  }
  trendInstance = echarts.init(taskTrendChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderWidth: 0,
      textStyle: { color: '#606266' }
    },
    legend: {
      data: ['发布任务', '完成任务'],
      bottom: 0,
      textStyle: { color: '#606266' }
    },
    grid: { left: '3%', right: '4%', bottom: '15%', top: '10%', containLabel: true },
    xAxis: {
      type: 'category',
      data: stats.value.trend.months,
      axisLine: { lineStyle: { color: '#DCDFE6' } },
      axisLabel: { color: '#606266' }
    },
    yAxis: {
      type: 'value',
      name: '数量',
      nameTextStyle: { color: '#606266' },
      axisLine: { lineStyle: { color: '#DCDFE6' } },
      axisLabel: { color: '#606266' },
      splitLine: { lineStyle: { color: '#EBEEF5' } }
    },
    series: [
      {
        name: '发布任务',
        type: 'line',
        smooth: true,
        data: stats.value.trend.publishedSeries,
        itemStyle: { color: '#409EFF' },
        lineStyle: { width: 3, shadowColor: '#409EFF30', shadowBlur: 8 },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#409EFF40' },
            { offset: 1, color: '#409EFF05' }
          ])
        },
        symbol: 'circle', symbolSize: 6
      },
      {
        name: '完成任务',
        type: 'line',
        smooth: true,
        data: stats.value.trend.finishedSeries,
        itemStyle: { color: '#67C23A' },
        lineStyle: { width: 3, shadowColor: '#67C23A30', shadowBlur: 8 },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#67C23A40' },
            { offset: 1, color: '#67C23A05' }
          ])
        },
        symbol: 'circle', symbolSize: 6
      }
    ]
  }
  trendInstance.setOption(option)
  window.addEventListener('resize', handleResize)
  setTimeout(() => trendInstance && trendInstance.resize(), 0)
}

// 初始化任务完成情况图
const initCompletionChart = () => {
  if (!completionChart.value) return
  if (completionInstance) {
    completionInstance.dispose()
    completionInstance = null
  }
  completionInstance = echarts.init(completionChart.value)

  const b = stats.value.buckets
  const option = {
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderWidth: 0,
      textStyle: { color: '#606266' },
      formatter: '{b}: {c}个 ({d}%)'
    },
    legend: { bottom: 0, textStyle: { color: '#606266' } },
    series: [{
      name: '任务状态',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['50%', '45%'],
      avoidLabelOverlap: false,
      itemStyle: { borderRadius: 6, borderColor: '#fff', borderWidth: 2 },
      label: { show: true, formatter: '{b}\n{c}个', color: '#606266' },
      labelLine: { lineStyle: { color: '#DCDFE6' } },
      emphasis: { label: { show: true, fontSize: 14, fontWeight: 'bold' } },
      data: [
        { value: b.completed,  name: '已完成', itemStyle: { color: '#67C23A' } },
        { value: b.inProgress, name: '进行中', itemStyle: { color: '#409EFF' } },
        { value: b.notStarted, name: '待开始', itemStyle: { color: '#909399' } },
        { value: b.disabled,   name: '已停用', itemStyle: { color: '#F56C6C' } }
      ]
    }]
  }
  completionInstance.setOption(option)
  window.addEventListener('resize', handleResize)
  setTimeout(() => completionInstance && completionInstance.resize(), 0)
}

onActivated(() => {
  handleResize()
})

onMounted(async () => {
  await loadTaskStats()
  await nextTick() // 确保图表容器 DOM 尺寸就绪
  initTaskTrendChart()
  initCompletionChart()
  loadRecentTasks()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  trendInstance && trendInstance.dispose()
  completionInstance && completionInstance.dispose()
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.stats-row {
  margin-bottom: 30px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  background: #fff;
  transition: all 0.3s ease;
  margin-bottom: 20px;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  }

  :deep(.el-card__body) {
    padding: 24px;
  }

  .stat-content {
    display: flex;
    align-items: center;

    .stat-icon {
      font-size: 48px;
      margin-right: 16px;
      padding: 8px;
      border-radius: 12px;
      background: rgba(64, 158, 255, 0.1);
    }

    .stat-info {
      flex: 1;

      .stat-value {
        font-size: 32px;
        font-weight: 700;
        line-height: 1.2;
        margin-bottom: 4px;
        color: #303133;
      }

      .stat-label {
        font-size: 14px;
        color: #909399;
        font-weight: 500;
      }
    }
  }
}

.charts-row {
  margin-bottom: 30px;
}

.chart-card {
  border-radius: 12px;
  border: none;
  background: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;

  :deep(.el-card__header) {
    border-bottom: 1px solid #EBEEF5;
    padding: 16px 20px;
  }

  .card-header {
    display: flex;
    align-items: center;

    .el-icon {
      margin-right: 8px;
      color: #409EFF;
      font-size: 18px;
    }
  }

  .card-title {
    font-weight: 600;
    color: #303133;
    font-size: 16px;
  }

  .chart-container {
    width: 100%;
    height: 350px;
  }
}

.table-card {
  border-radius: 12px;
  border: none;
  background: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

  :deep(.el-card__header) {
    border-bottom: 1px solid #EBEEF5;
    padding: 16px 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-title {
    font-weight: 600;
    color: #303133;
    font-size: 16px;
  }
}

@media (max-width: 768px) {
  .app-container {
    padding: 15px;
  }

  .stat-card .stat-content {
    .stat-icon {
      font-size: 36px;
      margin-right: 12px;
    }

    .stat-info .stat-value {
      font-size: 26px;
    }
  }

  .chart-container {
    height: 280px !important;
  }
}
</style>
